import { Button, Card, message, Select } from 'antd'
import React, { useEffect, useState } from 'react'
import useWebSocket from '@/hooks/UseWebsocket';
import { GetSetcardTimer } from '@/pages/account/Business/service';
import { useDetermineCardType } from '@/hooks/DetermineCardType';
import { Del, getmsg, SendCardInfo } from './request';
import { useIntl } from '@umijs/max';
interface Timelist {
    label: string,
    value: number
}
const index = () => {
    const intl = useIntl()
    const [sendMsg, setsendMsg] = useState<any>(''); // 发送消息
    const [CardMessage, setCardMessage] = useState(); // 接受消息
    const [type, setType] = useState<string>(''); // 成功后的提示消息

    const [cardNum, setcardNum] = useState("")
    const [_, sendMessage, lastMessage, isConnected] = useWebSocket({
        url: 'ws://127.0.0.1:9909',
        onOpen: () => {
            if (sendMsg) {
                sendMessage(sendMsg);
            }
        },
        onClose: () => {
            //连接关闭
            console.log('WebSocket disconnected');
        },
        onError: (event) => {
            //连接异常
            console.error('WebSocket error:', event);
        },
        onMessage: (onmsg) => {
            //收到消
            setCardMessage(JSON.parse(onmsg));
            // console.log(JSON.parse(onmsg))
        },
    });
    useEffect(() => {
        if (isConnected && sendMsg) {
            sendMessage(sendMsg);
        }
    }, [sendMsg, isConnected]);


    const GetCardMsg = async (cardid: string, type: number) => {
        let data = await getmsg(cardid)
      
        if (data.code == 0) {
            if (type == 1) {
                SendCard()
            } else {
                console.log("删除成功", cardid);

                let cldata = { "cardclass": "clearcard", "lockclass": "1", "shanqu": "1", "pass": "FFFFFFFFFFFF" ,"uuid":"111974"};
                setcardNum(cardid)
                setsendMsg(cldata);
                setType('退卡成功');
            }

        }

    }


    useEffect(() => {
        if (CardMessage) {

            let data = JSON.parse(lastMessage)
            if (data.result != 0) {
                if (type == "readCardType") {
                    if (data.msg == "空卡") {
                        GetCardMsg(data.cardid, 1)
                    }

                } else {

                    return message.error(data.msg)
                }


            }
            if (type == "readCardType") {
                if (data.hasOwnProperty("cardclass")) {
                    const [res] = useDetermineCardType(data.cardclass)
                    return message.error(intl.formatMessage({ id: 'Table.Return Room Card Loss' }, { card:res }))
                } else {
                    if (data.msg == "空卡") return
                    return message.error(data.msg)
                }
            }
            if (type == '校时卡,发卡成功') {
                SendCardInfo({
                    cardNum: data.cardid,
                    cmdInfo: JSON.stringify(sendMsg)
                })
                message.success(type)
            }
            if (type == 'tuika') {
                const [res] = useDetermineCardType(data.cardclass)
                if (data.cardclass != "setcard") return message.error(intl.formatMessage({ id: 'Table.Room Card Loss' }, { card:res }))
                GetCardMsg(data.cardid, 2)

            }

            if (type == '退卡成功') {

                Del(cardNum)
                message.success(type)
            }

        }
    }, [CardMessage]);

    const SendCard = async () => {
        let Result = await GetSetcardTimer(cardtime)
        if (Result.code == 0) {
            const dataMSG: any = {
                cardclass: 'setcard',
                uuid: 'setcard',
                setlocktime: Result.data.now,
            };
            setsendMsg(dataMSG);
            setType('校时卡,发卡成功');
        }

    }

    const TimerSer = () => {
        let data = { "cardclass": "readcard", "uuid": "setcard963", "isclear": "0" }

        setsendMsg(data);

        setType('readCardType');
    }

    const readCard = () => {
        let data = { "cardclass": "readcard", "uuid": "setcard963", "isclear": "0" }
        setsendMsg(data)
        setType("tuika")
    }

    const div = (
        <div>
            {intl.formatMessage({id:"card.Hour card"})} <div style={{
                fontSize: "14px",
                backgroundColor: "#F5F5F5",
                fontWeight: "200",
                margin: "10px 0 10px 0"
            }}

            > {intl.formatMessage({id:"ManageCards.Hour title"})}
            </div>
        </div>
    )

    const [cardtime, setCardtime] = useState<number>(10)
    const [timeList] = useState<Timelist[]>([])

    for (var i = 1; i <= 60; i++) {

        if (i % 5 == 0) {

            timeList.push({
                label: i +intl.formatMessage({id:"card.minute"}),
                value: i
            })
        }
    }

    const SelectTime = (value: number) => {
        setCardtime(value)

    }


    return (
        <Card title={div} style={{ height: "100%" }} headStyle={{
            backgroundColor: "#F5F5F5"
        }}>
            <div >

                <div style={{ fontSize: "16px", marginBottom: "6px" }}> {intl.formatMessage({id:"ManageCards.Select a delay duration"})} </div>

                <Select
                    defaultValue={cardtime}
                    style={{ width: 160 }}
                    onChange={SelectTime}
                    options={timeList}
                />
                <div>
                </div>
            </div>
            <br />

            <Button type="primary" onClick={TimerSer}>{intl.formatMessage({id:"ManageCards.Hour card"})}</Button> &emsp;&emsp;&emsp;&emsp;&emsp;
            <Button type="primary" danger onClick={readCard}>{intl.formatMessage({id:"ManageCards.Return Hour card"})}</Button>
        </Card>
    )
}

export default index
